<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter"
      :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div v-show="showSearch" class="mb-[10px]">
        <el-card shadow="hover">
          <el-form ref="queryFormRef" :model="queryParams" :inline="true">
            <el-form-item label="家属姓名" prop="name">
              <el-input v-model="queryParams.name" placeholder="请输入家属姓名" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="联系电话" prop="phone">
              <el-input v-model="queryParams.phone" placeholder="请输入联系电话" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
              <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </div>
    </transition>

    <el-card shadow="never">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" plain icon="Plus" @click="handleAdd"
              v-hasPermi="['cemetery:relation:add']">新增</el-button>
          </el-col>
          <!-- <el-col :span="1.5">
            <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate()" v-hasPermi="['cemetery:relation:edit']">修改</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete()" v-hasPermi="['cemetery:relation:remove']">删除</el-button>
          </el-col> -->
          <el-col :span="1.5">
            <el-button v-hasPermi="['tool:gen:import']" type="info" plain icon="Upload"
              @click="handleImport">导入</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="warning" plain icon="Download" @click="handleExport"
              v-hasPermi="['cemetery:relation:export']">导出</el-button>
          </el-col>
          <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>
      </template>

      <el-table v-loading="loading" border :data="relationList">
        <el-table-column label="序号" type="index" width="55" align="center" />
        <el-table-column label="家属姓名" align="center" prop="name" />
        <el-table-column label="联系电话" align="center" prop="phone" />
        <el-table-column label="身份证号" align="center" prop="idCard" />
        <el-table-column label="性别" align="center" prop="sex">
          <template #default="scope">
            <span>{{ scope.row.sex == 1 ? '女' : '男' }}</span>
          </template>
        </el-table-column>
        <el-table-column label="年龄" align="center" prop="age" />
        <el-table-column label="住址" align="center" prop="site" />
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-tooltip content="修改" placement="top">
              <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)"
                v-hasPermi="['cemetery:relation:edit']"></el-button>
            </el-tooltip>
            <!-- <el-tooltip content="关联逝者" placement="top">
              <el-button link type="primary" icon="Link" @click="handleDelete(scope.row)"
                v-hasPermi="['cemetery:relation:remove']"></el-button>
            </el-tooltip> -->
            <el-tooltip content="删除" placement="top">
              <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)"
                v-hasPermi="['cemetery:relation:remove']"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize" @pagination="getList" />
    </el-card>
    <!-- 添加或修改家属信息对话框 -->
    <el-dialog :title="dialog.title" v-model="dialog.visible" width="1200px" append-to-body>
      <el-form ref="relationFormRef" :model="form" :rules="rules" label-width="80px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="姓名" prop="name">
              <el-input v-model="form.name" placeholder="请输入姓名" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="联系电话" prop="phone">
              <el-input v-model="form.phone" placeholder="请输入联系电话" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="身份证号" prop="idCard">
              <el-input v-model="form.idCard" placeholder="请输入身份证号" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="年龄" prop="age">
              <el-input-number v-model="form.age" :min="1" :max="999" :step-strictly="true" :step="1"
                placeholder="请输入逝者年龄" style="width: 100%;">
              </el-input-number>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="性别" prop="sex">
              <el-radio-group v-model="form.sex">
                <el-radio value="0">男</el-radio>
                <el-radio value="1">女</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="住址" prop="site">
              <el-input v-model="form.site" placeholder="请选择住址" :disabled="!form.latitude||!form.longitude">
                <template #append>
                  <el-icon style="cursor: pointer;" @click="chooseMap">
                    <Location />
                  </el-icon>
                </template>
              </el-input>
            </el-form-item>
          </el-col>
          <!-- <el-col :span="12">
            <el-form-item label="经度" prop="longitude">
              <el-input v-model="form.longitude" placeholder="请输入经度" />
            </el-form-item>
            <el-form-item label="纬度" prop="latitude">
              <el-input v-model="form.latitude" placeholder="请输入纬度" />
            </el-form-item>
            <el-form-item label="备注" prop="remark">
              <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
            </el-form-item>
          </el-col> -->
        </el-row>
        <div style="display: flex; align-items: center;">
          <h3 style="margin-right: 10px;">关联逝者信息</h3>
          <el-button type="primary" plain icon="Plus" @click="handleAddRelation">添加</el-button>
        </div>
        <el-table border :data="addRelationList">
          <el-table-column label="序号" type="index" width="55" align="center" />
          <el-table-column label="逝者姓名" align="center" prop="name">
            <template #default="scope">
              <span>{{scope.row.name}}</span>
              <!-- <el-button v-else link type="primary" @click="openDeadPerson()">选择</el-button> -->
            </template>
          </el-table-column>
          <el-table-column label="逝者性别" align="center" prop="sex">
            <template #default="scope">
              <span>{{ scope.row.sex == '1' ? '女' : scope.row.sex == '0' ? '男' : '' }}</span>
            </template>
          </el-table-column>
          <el-table-column label="逝者年龄" align="center" prop="age" />
          <el-table-column label="死亡日期" align="center" prop="deathDate">
            <template #default="scope">
              <span>{{ parseTime(scope.row.deathDate, '{y}-{m}-{d}') }}</span>
            </template>
          </el-table-column>
          <el-table-column label="安葬位置" align="center" prop="graveName"></el-table-column>
          <el-table-column label="与逝者关系" align="center" prop="relation">
            <template #default="scope">
              <el-input v-model="scope.row.relation" placeholder="与逝者关系" maxlength="5" minlength="2" />
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
            <template #default="scope">
              <el-button link type="primary" @click="handleDeadDelete(scope.$index,scope.row)">移除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
    <!-- 逝者信息对话框 -->
    <el-dialog :title="dialogDead.title" v-model="dialogDead.visible" width="1200px" append-to-body>
      <el-form ref="queryDeadFormRef" :model="queryDeadParams" :inline="true">
        <el-form-item label="逝者姓名" prop="name">
          <el-input v-model="queryDeadParams.name" placeholder="请输入逝者姓名" clearable @keyup.enter="handleDeadQuery"
            style="width: 180px;" />
        </el-form-item>
        <el-form-item label="安葬位置" prop="graveName">
          <el-input v-model="queryDeadParams.graveName" placeholder="请输入安葬位置" clearable @keyup.enter="handleDeadQuery"
            style="width: 180px;" />
        </el-form-item>
        <el-form-item label="死亡日期" prop="deathDate">
          <el-date-picker clearable v-model="queryDeadParams.deathDate" type="date" value-format="YYYY-MM-DD"
            placeholder="请选择死亡日期" style="width: 180px;" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="Search" @click="handleDeadQuery">搜索</el-button>
          <el-button icon="Refresh" @click="resetDeadQuery">重置</el-button>
        </el-form-item>
      </el-form>
      <el-table border ref="tableRef" :data="deadPersonList"
        @selection-change="handleSelectionChange"
        row-key="id">
        <el-table-column type="selection" width="55" align="center" :reserve-selection="true" />
        <el-table-column label="逝者姓名" align="center" prop="name" />
        <el-table-column label="逝者性别" align="center" prop="sex">
          <template #default="scope">
            <span>{{ scope.row.sex == 1 ? '女' : '男' }}</span>
          </template>
        </el-table-column>
        <el-table-column label="逝者年龄" align="center" prop="age" />
        <el-table-column label="身份证号" align="center" prop="idCard" />
        <el-table-column label="出生日期" align="center" prop="birthDate">
          <template #default="scope">
            <span>{{ parseTime(scope.row.birthDate, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="死亡日期" align="center" prop="deathDate">
          <template #default="scope">
            <span>{{ parseTime(scope.row.deathDate, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="安葬日期" align="center" prop="burialDate">
          <template #default="scope">
            <span>{{ parseTime(scope.row.burialDate, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="安葬位置" align="center" prop="graveName" />
        <!-- <el-table-column label="关联家属" align="center" prop="name" />
        <el-table-column label="家属电话" align="center" prop="name" /> -->
      </el-table>
      <pagination v-show="deadPersonTotal > 0" :total="deadPersonTotal" v-model:page="queryDeadParams.pageNum"
        v-model:limit="queryDeadParams.pageSize" @pagination="getDeadPersonList" />

      <h3>已选择逝者:</h3>
      <el-row>
        <el-button type="primary" v-for="(item,index) in chooseDeadList" :key="index">
          {{item.name}}
          <el-icon style="margin-left: 10px;" @click="delDealList(index,item)">
            <Close />
          </el-icon>
        </el-button>
      </el-row>

      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitDeadForm">确 定</el-button>
        </div>
      </template>
    </el-dialog>
    <!-- 地图对话框 -->
    <el-dialog :title="mapDialog.title" v-model="mapDialog.visible" v-if="mapDialog.visible" width="800px"
      append-to-body>
      <MapPicker @point-selected="handlePointSelected" :longitude="form.longitude" :latitude="form.latitude" />
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitLocation">确 定</el-button>
          <el-button @click="dialog.visible = false">取 消</el-button>
        </div>
      </template>
      <!-- <div v-if="currentLocation" class="location-display">
        <h3>已选择的位置:</h3>
        <p>经度: {{ currentLocation.lng }}</p>
        <p>纬度: {{ currentLocation.lat }}</p>
        <p>地址: {{ currentLocation.address }}</p>
        <button @click="submitLocation">确认选择</button>
      </div> -->
    </el-dialog>
    <!-- 用户导入对话框 -->
    <el-dialog v-model="upload.open" :title="upload.title" width="400px" append-to-body>
      <el-upload ref="uploadRef" :limit="1" accept=".xlsx, .xls" :headers="upload.headers"
        :action="upload.url + '?updateSupport=' + upload.updateSupport" :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress" :on-success="handleFileSuccess" :auto-upload="false" drag>
        <el-icon class="el-icon--upload">
          <i-ep-upload-filled />
        </el-icon>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <template #tip>
          <div class="text-center el-upload__tip">
            <div class="el-upload__tip"><el-checkbox v-model="upload.updateSupport" />是否更新已经存在的用户数据</div>
            <span>仅允许导入xls、xlsx格式文件。</span>
            <el-link type="primary" :underline="false" style="font-size: 12px; vertical-align: baseline"
              @click="importTemplate">下载模板</el-link>
          </div>
        </template>
      </el-upload>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitFileForm">确 定</el-button>
          <el-button @click="upload.open = false">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Relation" lang="ts">
  import { listRelation, getRelation, delRelation, addRelation, updateRelation } from '@/api/cemetery/relation';
  import { RelationVO, RelationQuery, RelationForm } from '@/api/cemetery/relation/types';
  import { listDeadPerson, getDeadPerson, delDeadPerson, addDeadPerson, updateDeadPerson, getTemplate } from '@/api/cemetery/deadPerson';
  import { DeadPersonVO, DeadPersonQuery, DeadPersonForm } from '@/api/cemetery/deadPerson/types';
  import { globalHeaders } from '@/utils/request';
  const { proxy } = getCurrentInstance() as ComponentInternalInstance;

  const relationList = ref<RelationVO[]>([]);
  const deadPersonList = ref<DeadPersonVO[]>([]);
  const buttonLoading = ref(false);
  const loading = ref(true);
  const showSearch = ref(true);
  const ids = ref<Array<string | number>>([]);
  const single = ref(true);
  const multiple = ref(true);
  const total = ref(0);
  const deadPersonTotal = ref(0);
  const templateUrl = ref('')


  const currentLocation = ref(null);

  const queryFormRef = ref<ElFormInstance>();
  const relationFormRef = ref<ElFormInstance>();
  const uploadRef = ref<ElUploadInstance>();
  const tableRef = ref()

  const addRelationList = ref([])

  const dialog = reactive<DialogOption>({
    visible: false,
    title: ''
  });

  const dialogDead = reactive<DialogOption>({
    visible: false,
    title: '请选择逝者信息'
  });

  const mapDialog = reactive<DialogOption>({
    visible: false,
    title: ''
  });

  const validateIdCard = (rule, value, callback) => {
    // 验证身份证号
    if (!validateIdCardFun(value)) {
      return callback(new Error('身份证号码不合法'));
    }

    // 统一处理为字符串并去除空格
    value = value.toString().replace(/[\s-]/g, '');

    let birthDate, age, gender, sex;

    // 处理15位身份证
    if (value.length === 15) {
      // 15位身份证：7-12位是生日，格式YYMMDD
      const birthYear = '19' + value.substr(6, 2);
      const birthMonth = value.substr(8, 2);
      const birthDay = value.substr(10, 2);
      birthDate = new Date(`${birthYear}-${birthMonth}-${birthDay}`);

      // 性别：第15位，奇数为男，偶数为女
      gender = parseInt(value.charAt(14)) % 2 === 1 ? '男' : '女';
      sex = parseInt(value.charAt(16)) % 2 === 1 ? '0' : '1';
    }
    // 处理18位身份证
    else if (value.length === 18) {
      // 18位身份证：7-14位是生日，格式YYYYMMDD
      const birthYear = value.substr(6, 4);
      const birthMonth = value.substr(10, 2);
      const birthDay = value.substr(12, 2);
      birthDate = new Date(`${birthYear}-${birthMonth}-${birthDay}`);

      // 性别：第17位，奇数为男，偶数为女
      gender = parseInt(value.charAt(16)) % 2 === 1 ? '男' : '女';
      sex = parseInt(value.charAt(16)) % 2 === 1 ? '0' : '1';
    }

    // 计算年龄
    const today = new Date();
    let ageTemp = today.getFullYear() - birthDate.getFullYear();
    const monthDiff = today.getMonth() - birthDate.getMonth();

    // 如果生日还没过，年龄减1
    if (monthDiff < 0 || (monthDiff === 0 && today.getDate() < birthDate.getDate())) {
      ageTemp--;
    }
    age = ageTemp;

    // 格式化出生日期为YYYY-MM-DD
    const formattedDate = `${birthDate.getFullYear()}-${(birthDate.getMonth() + 1).toString().padStart(2, '0')}-${birthDate.getDate().toString().padStart(2, '0')}`;

    console.log(Number.isNaN(age), Number.isNaN(sex))
    form.value.age = Number.isNaN(age) ? '' : age
    form.value.sex = Number.isNaN(sex) ? '' : sex

    return callback();
    // return {
    //   birthDate: formattedDate,
    //   age: age,
    //   gender: gender,
    // };
  }

  // 验证函数：仅允许中英文，长度2-20
  const validateName = (rule, value, callback) => {
    if (!value) {
      return callback(new Error('请输入内容'));
    }
    // 正则表达式：匹配中文字符和英文字母
    const reg = /^[\u4e00-\u9fa5a-zA-Z]+$/;

    if (!reg.test(value)) {
      callback(new Error('仅允许输入中文或英文'));
    } else if (value.length < 2 || value.length > 20) {
      callback(new Error('长度需在2到20个字符之间'));
    } else {
      callback();
    }
  };
  // 验证函数：仅允许数字，长度6-20
  const validateNumber = (rule, value, callback) => {
    if (!value) {
      return callback(new Error('请输入数字'));
    }
    // 检查是否为纯数字
    if (!/^\d+$/.test(value)) {
      callback(new Error('只能输入数字'));
    }
    // 检查长度
    else if (value.length < 6) {
      callback(new Error('最少需要6位数字'));
    }
    else if (value.length > 20) {
      callback(new Error('最多不能超过20位数字'));
    }
    else {
      callback();
    }
  };

  const queryDeadParams = ref({
    name: '',
    location: '',
    deathDate: '',
    pageNum: 1,
    pageSize: 10,
  })
  const queryDeadFormRef = ref(null);
  const chooseDeadList = ref([]);
  // 保存所有选中的ID
  const selectedIds = ref(new Set());
  const delA = ref(false)

  const initFormData : RelationForm = {
    id: undefined,
    name: undefined,
    phone: undefined,
    idCard: undefined,
    age: undefined,
    sex: undefined,
    site: undefined,
    longitude: undefined,
    latitude: undefined,
    remark: undefined,
    deadRelationBos: [],
  }
  const data = reactive<PageData<RelationForm, RelationQuery>>({
    form: { ...initFormData },
    queryParams: {
      pageNum: 1,
      pageSize: 10,
      name: undefined,
      phone: undefined,
      idCard: undefined,
      age: undefined,
      sex: undefined,
      site: undefined,
      longitude: undefined,
      latitude: undefined,
      params: {
      }
    },
    rules: {
      name: [
        { required: true, message: "姓名不能为空", trigger: "blur" },
        { validator: validateName, trigger: 'blur' }
      ],
      phone: [
        { required: true, message: "联系电话不能为空", trigger: "blur" },
        // {
        //   pattern: /^1[3456789]\d{9}$/,
        //   message: '请输入正确的电话号码',
        // }
        { validator: validateNumber, trigger: 'blur' }
      ],
      idCard: [
        { required: true, message: "身份证号不能为空", trigger: "blur" },
        { validator: validateIdCard, trigger: 'blur' },
      ],
      age: [
        { required: true, message: "年龄不能为空", trigger: "blur" }
      ],
      sex: [
        { required: true, message: "用户性别不能为空", trigger: "change" }
      ],
      site: [
        { required: true, message: "位置不能为空", trigger: "blur" }
      ],
      longitude: [
        { required: true, message: "经度不能为空", trigger: "blur" }
      ],
      latitude: [
        { required: true, message: "纬度不能为空", trigger: "blur" }
      ],
      remark: [
        { required: true, message: "备注不能为空", trigger: "blur" }
      ],
    }
  });
  /*** 用户导入参数 */
  const upload = reactive<ImportOption>({
    // 是否显示弹出层（用户导入）
    open: false,
    // 弹出层标题（用户导入）
    title: '',
    // 是否禁用上传
    isUploading: false,
    // 是否更新已经存在的用户数据
    updateSupport: 0,
    // 设置上传的请求头部
    headers: globalHeaders(),
    // 上传的地址
    url: import.meta.env.VITE_APP_BASE_API + '/system/user/importData'
  });
  const { queryParams, form, rules } = toRefs(data);


  const validateIdCardFun = (idCard) => {
    // 去除空格和特殊字符
    idCard = idCard.replace(/[\s-]/g, '');

    // 基本格式校验
    // if (!/^(\d{15}|\d{17}[\dXx])$/.test(idCard)) {
    //   return false;
    // }
    // 如果是15位，直接返回true（15位没有校验位）
    if (idCard.length === 15) {
      return true;
    }

    if (idCard.length === 18) {
      if (!/^[1-9]\d{5}(18|19|20)\d{2}(0[1-9]|1[0-2])(0[1-9]|[12]\d|3[01])\d{3}[\dXx]$/.test(idCard)) {
        return false;
      } else {
        return true;
      }
    }

    // 18位身份证校验位验证
    const weights = [7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2];
    const checkCodes = ['1', '0', 'X', '9', '8', '7', '6', '5', '4', '3', '2'];

    let sum = 0;
    for (let i = 0; i < 17; i++) {
      sum += parseInt(idCard.charAt(i)) * weights[i];
    }

    const mod = sum % 11;
    const checkCode = checkCodes[mod];

    return idCard.charAt(17).toUpperCase() === checkCode;
  }
  /** 查询家属信息列表 */
  const getList = async () => {
    loading.value = true;
    const res = await listRelation(queryParams.value);
    relationList.value = res.rows;
    total.value = res.total;
    loading.value = false;
  }

  /** 取消按钮 */
  const cancel = () => {
    reset();
    dialog.visible = false;
  }

  /** 表单重置 */
  const reset = () => {
    form.value = { ...initFormData };
    relationFormRef.value?.resetFields();
  }

  /** 搜索按钮操作 */
  const handleQuery = () => {
    queryParams.value.pageNum = 1;
    getList();
  }

  /** 重置按钮操作 */
  const resetQuery = () => {
    queryFormRef.value?.resetFields();
    handleQuery();
  }



  /** 新增按钮操作 */
  const handleAdd = () => {
    reset();
    dialog.visible = true;
    addRelationList.value = []
    dialog.title = "添加家属信息";
  }
  const chooseMap = () => {
    mapDialog.visible = true;
    mapDialog.title = "选择位置";
  }
  const handlePointSelected = (location) => {
    currentLocation.value = location
    console.log('选择的位置:', location)
  }
  const submitLocation = () => {
    form.value.site = currentLocation.value.address
    form.value.longitude = currentLocation.value.lng
    form.value.latitude = currentLocation.value.lat
    mapDialog.visible = false
  }

  /** 修改按钮操作 */
  const handleUpdate = async (row ?: RelationVO) => {
    reset();
    const _id = row?.id || ids.value[0]
    const res = await getRelation(_id);
    Object.assign(form.value, res.data);
    addRelationList.value = form.value.deadPersonList
    dialog.visible = true;
    dialog.title = "修改家属信息";
  }

  /** 提交按钮 */
  const submitForm = () => {
    relationFormRef.value?.validate(async (valid : boolean) => {
      if (valid) {
        if (addRelationList.value.length > 0) {
          for (let item of addRelationList.value) {
            if (!item.relation) {
              proxy?.$modal.msgError("与逝者关系不能为空");
              return false
            } else {
              form.value.deadRelationBos.push({
                deadPersonId: item.id,
                relation: item.relation
              })
            }
          }
          delete form.value.deadPersonList
        }
        buttonLoading.value = true;
        if (form.value.id) {
          await updateRelation(form.value).finally(() => buttonLoading.value = false);
        } else {
          await addRelation(form.value).finally(() => buttonLoading.value = false);
        }
        proxy?.$modal.msgSuccess("操作成功");
        dialog.visible = false;
        await getList();
      }
    });
  }

  /** 删除按钮操作 */
  const handleDelete = async (row ?: RelationVO) => {
    const _ids = row?.id || ids.value;
    await proxy?.$modal.confirm('是否确认删除家属信息编号为"' + _ids + '"的数据项？').finally(() => loading.value = false);
    await delRelation(_ids);
    proxy?.$modal.msgSuccess("删除成功");
    await getList();
  }
  /**获取模板地址**/
  const getTemplateUrl = async () => {
    const params = {
      pageNum: 1,
      pageSize: 10,
      dictTyp: 'template',
      dictLabel: 'deadPerson',
    }
    const res = await getTemplate(params);
    templateUrl.value = res.rows[0].dictValue
  }
  /** 下载模板操作 */
  const importTemplate = () => {
    //proxy?.download('system/dict/data/list?pageNum=1&pageSize=10&dictType=template&dictLabel=deadPerson', {}, `user_template_${new Date().getTime()}.xlsx`);
    window.open(templateUrl.value)
  };

  /** 提交上传文件 */
  function submitFileForm() {
    uploadRef.value?.submit();
  }
  /**文件上传中处理 */
  const handleFileUploadProgress = () => {
    upload.isUploading = true;
  };
  /** 文件上传成功处理 */
  const handleFileSuccess = (response : any, file : UploadFile) => {
    upload.open = false;
    upload.isUploading = false;
    uploadRef.value?.handleRemove(file);
    ElMessageBox.alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + response.msg + '</div>', '导入结果', {
      dangerouslyUseHTMLString: true
    });
    getList();
  };
  /** 导出按钮操作 */
  const handleExport = () => {
    proxy?.download('cemetery/relation/export', {
      ...queryParams.value
    }, `relation_${new Date().getTime()}.xlsx`)
  }

  //添加逝者关系
  const handleAddRelation = () => {
    // addRelationList.value.push({
    //   name: '',
    //   sex: '',
    //   age: '',
    //   deathDate: '',
    //   location: '',
    //   relation: '',
    // })
    dialogDead.visible = true;
    getDeadPersonList()
  }
  //选择
  const openDeadPerson = () => {
    dialogDead.visible = true;
    getDeadPersonList()
  }
  /** 查询逝者信息列表 */
  const getDeadPersonList = async () => {
    const res = await listDeadPerson(queryDeadParams.value);
    deadPersonList.value = res.rows;
    deadPersonTotal.value = res.total;
    checkFun()
  }
  /** 搜索按钮操作 */
  const handleDeadQuery = () => {
    queryDeadParams.value.pageNum = 1;
    getDeadPersonList();
  }

  /** 重置按钮操作 */
  const resetDeadQuery = () => {
    queryDeadFormRef.value?.resetFields();
    handleDeadQuery();
  }
  /** 多选框选中数据 */
  const handleSelectionChange = (selection : DeadPersonVO[]) => {
    // ids.value = selection.map(item => item.id);
    // single.value = selection.length != 1;
    // multiple.value = !selection.length;
    // selectedIds.value.clear();
    // // 添加所有选中行的ID
    // selection.forEach(row => {
    //   selectedIds.value.add(row.id);
    // });
    // const rids = chooseDeadList.value.map(item => item.id);
    // selection.forEach((item, index) => {
    //   if (!rids.includes(item.id)) {
    //     chooseDeadList.value = chooseDeadList.value.concat(item)
    //   }
    // })
    // if( delA.value ){
    //   delA.value = false

    //   return false
    // }else{
    //   console.log('111111111111111')


    //   chooseDeadList.value = [...new Map(selection.map(item => [item.id, item])).values()];
    // }

    chooseDeadList.value = tableRef.value.getSelectionRows()
  }
  const submitDeadForm = () => {
    const rids = addRelationList.value.map(item => item.id);
    chooseDeadList.value.forEach((item, index) => {
      if (!rids.includes(item.id)) {
        addRelationList.value = addRelationList.value.concat(item)
      }
    })
    dialogDead.visible = false;
  }
  const handleDeadDelete = (index, row) => {
    addRelationList.value.splice(index, 1)
  }
  const delDealList = (index, item) => {
    chooseDeadList.value.splice(index, 1)
    delA.value = true
    console.log('下面列表', chooseDeadList.value)
    // getDeadPersonList()
    const rids = chooseDeadList.value.map(item => item.id);
    console.log(rids)
    deadPersonList.value.forEach(row => {
      if (rids.includes(row.id)) {
        tableRef.value.toggleRowSelection(row, true);
        console.log(222222)
        // delA.value = false

      } else {
        tableRef.value.toggleRowSelection(row,false);
        console.log(222222)

      }
    })


  }
  const checkFun = () => {
    const rids = chooseDeadList.value.map(item => item.id);
    console.log(rids)
    deadPersonList.value.forEach(row => {
      if (rids.includes(row.id)) {
        tableRef.value.toggleRowSelection(row, true);
      } else {
        tableRef.value.toggleRowSelection(row,false);
      }
    })
  }

  onMounted(() => {
    getList();
  });
</script>

